//与预约相关的逻辑
var appointingApp = angular.module("appointingApp",[]);
//开始预约
appointingApp.controller("beAppointingController",function($scope,$http,scCodeService,$location,$state,Popup,$stateParams){
	//$scope.loadingToastSet("预约中...");
	//$scope.loadingToastHide();
	//获取token
    var token = localStorage.getItem("token");
    //获取用户卡号
    var userCard = localStorage.getItem("cardNo");
    //獲取用戶id
    var userId = localStorage.getItem("userId");
    var chargerId=localStorage.getItem("charger_chargerId");
    //webSocket
	var webSocket = new WebSocket("ws://" + window.location.host + "/appserver/static/websocket/" + userId);
    webSocket.onerror = function(event) {
        console.log("error:" + event.data)
    };
    webSocket.onopen = function(event) {
        console.log("连接建立成功");
    };
    webSocket.onmessage = function(event) {
        console.log("webSocket data is "+event.data);
        var websocketdata=JSON.parse(event.data);
        var websocketdata_data=JSON.parse(websocketdata.data);
        //console.log("webSocket data string is "+websocketdata);
        if(websocketdata.action == "1001"){   //预约成功推送
            chargeSn = websocketdata_data.reservationSn;
            //alert("websocket chargeSn:"+chargeSn);
            console.log("websocket reservationSn :"+reservationSn);
            localStorage.setItem("reservationSn", reservationSn);
            window.location.href=mainConfig.hostUrl+"index.html?#/appointing/" + reservationSn;
        }else if(websocketdata.action == "1002"){   //开启充电成功推送
            chargeSn = websocketdata_data.chargeSn;
            //alert("websocket chargeSn:"+chargeSn);
            console.log("websocket chargeSn :"+chargeSn);
            localStorage.setItem("chargeSn", chargeSn);
        }else if(websocketdata.action == "1003"){    //结束充电成功推送
            var orderNo = websocketdata_data.orderNo;
            localStorage.setItem("orderNo",orderNo);
            //alert("websocket orderNo:"+orderNo);
            console.log("websocket orderNo :"+orderNo);
            $scope.openCharge = "false";
            localStorage.setItem("openCharge", $scope.openCharge);
            window.location.href=mainConfig.hostUrl+"index.html?#/orderPay/" + orderNo;        
        }
        
    };
	//获取桩站信息
	$scope.getChargerDetail=function () {
		$scope.qrCode=localStorage.getItem("charger_qrCode");
		console.log($scope.qrCode);
		var postData = {
			qrCode:$scope.qrCode
		}
		scCodeService.getChargerDetailByQrCode(postData).then(function(data){
				console.log(data.data);
				if(data.code == "200"){
					 if(data.data){
						$scope.chargerDetail=data.data;
						console.log($scope.chargerDetail);
						//组装桩类型数据
						if($scope.chargerDetail.chargerType=="1"){
							$scope.chargerDetailType="直流 快充"
						}else if($scope.chargerDetail.chargerType=="2"){
							$scope.chargerDetailType="交流220V 慢充"
						}
					}
				}else{
					Popup.notice('获取桩信息失败', 3000, function() {
                            console.log('ok')
                    	});
				}
			})
	}
	$scope.getChargerDetail();
	//获取预约费率
    $scope.getRate = function() {
        var postData = {
            chargerId: chargerId
        }
        scCodeService.getRate(postData).then(function(data) {
        	if(data.code=="200"){
	            //费率处理
	            for (var i = 0; i < data.data.length; i++) {
	                if (data.data[i].feeType == 3) {
	                    $scope.mainRate.serveRate = data.data[i].rate;
	                }else if (data.data[i].feeType == 2) {
	                    $scope.mainRate.chargerRate = data.data[i].rate;
	                }else  if (data.data[i].feeType == 1) {
	                    $scope.mainRate.reservationRate = data.data[i].rate;
	                }
	            }
	            
	        }else{
	        	Popup.notice('获取桩信息失败', 3000, function() {
	                            console.log('ok')
	                    	});
	        }
        });
       
    }
    $scope.getRate();
	//开始导航
	$scope.satNavigation=function (argument) {
		//起点
		$scope.startcoordinate=localStorage.getItem("startcoordinate");
		//终点
		$scope.endcoordinate=$scope.chargerDetail.coordinate;
		//跳转到高德地图api导航
		window.location.href="http://gaode.com/?r=39.904777,116.42526700000002,起点,39.99458,116.30444299999999,终点,0,0,,,,src=jsapi_r_0"
	}
    //开始预约
    $scope.startReservation=function () {
    	$scope.loadingToastSet("预约中...");
    	var postData={
    		userCard:userCard,
    		chargerId:chargerId,
    		plugNo:$scope.chargerDetail.plugNoList[0].portNo
    	}
    	scCodeService.startReservation(postData).then(function(data) {
    		
            if(data.code=="200"){
				localStorage.setItem("chargerDetail",JSON.stringify($scope.chargerDetail));
				localStorage.setItem("mainRate",JSON.stringify($scope.mainRate));
	            //等待预约成功推送，如超过20s则调用查询正在进行中的业务查询接口，跳转至预约中界面，如查询无果，则跳转至我的订单中进行中tab
	            var num = 0;
                var pushTimeout = setInterval(function() {
                	num++;
                    if (num > 20) {
                        console.log(orderNo);
                        // alert("+++");
                       	clearInterval(pushTimeout);

                       	var postData={userCard:userCard}
						scCodeService.getOngoingOperation(postData).then(function(data){
							console.log(data.data);
							if(data.code == "200"){
									if(data.data){
									$scope.reservationSn=data.data.reservationList.reservationSn;
									window.location.href = mainConfig.hostUrl+"index.html?#/appointing/" + $scope.reservationSn;
								}
							}else{
								$location.path("/myOrder/processing");
							}
						})
                       	
                     }
                }, 1000);
	        }else if(data.code=="300"){
	        	$scope.loadingToastHide();
	        	Popup.notice('该桩正在充电中，不能预约', 3000, function() {
	                            console.log('ok')
	                    	});
	        }else if(data.code=="300"){
	        	$scope.loadingToastHide();
	        	Popup.notice('该桩正在预约中，不能预约', 3000, function() {
	                            console.log('ok')
	                    	});
	        }else{
	        	$scope.loadingToastHide();
	        	Popup.notice('预约失败', 3000, function() {
	                            console.log('ok')
	                    	});
	        }
        });
    }
});

//预约中
appointingApp.controller("appointingController",function($scope,$http,scCodeService,$location,$state,Popup,$stateParams){
	//$scope.loadingToastSet("订单推送中...");
	//$scope.loadingToastHide();
	//获取token
    var token = localStorage.getItem("token");
    //获取用户卡号
    var userCard = localStorage.getItem("cardNo");
    //獲取用戶id
    var userId = localStorage.getItem("userId");
	//是否正在充电
    var openCharge = localStorage.getItem("openCharge");
    $scope.isReservationNotOverTime="true"; //预约是否超时
    //webSocket
	var webSocket = new WebSocket("ws://" + window.location.host + "/appserver/static/websocket/" + userId);
    webSocket.onerror = function(event) {
        console.log("error:" + event.data)
    };
    webSocket.onopen = function(event) {
        console.log("连接建立成功");
    };
    webSocket.onmessage = function(event) {
        console.log("webSocket data is "+event.data);
        var websocketdata=JSON.parse(event.data);
        var websocketdata_data=JSON.parse(websocketdata.data);
        //console.log("webSocket data string is "+websocketdata);
        if(websocketdata.action == "1001"){   //预约成功推送
            chargeSn = websocketdata_data.reservationSn;
            //alert("websocket chargeSn:"+chargeSn);
            console.log("websocket reservationSn :"+reservationSn);
            localStorage.setItem("reservationSn", reservationSn);
            window.location.href=mainConfig.hostUrl+"index.html?#/appointing/" + reservationSn;
        }else if(websocketdata.action == "1002"){   //开启充电成功推送
            chargeSn = websocketdata_data.chargeSn;
            //alert("websocket chargeSn:"+chargeSn);
            console.log("websocket chargeSn :"+chargeSn);
            localStorage.setItem("chargeSn", chargeSn);
        }else if(websocketdata.action == "1003"){    //结束充电成功推送
            var orderNo = websocketdata_data.orderNo;
            localStorage.setItem("orderNo",orderNo);
            //alert("websocket orderNo:"+orderNo);
            console.log("websocket orderNo :"+orderNo);
            $scope.openCharge = "false";
            localStorage.setItem("openCharge", $scope.openCharge);
            window.location.href=mainConfig.hostUrl+"index.html?#/orderPay/" + orderNo;        
        }
        
    };
    //价格数据处理，从2处理成2.00格式
	$scope.intToFloat=function(num){
		num=Math.round(num*100)/100;
		var obj=num.toString().split(".");
		if(obj.length==1){
			num=num+'.00';
		}else{
			if(obj[1].length==1){
				num=num+'0';
			}
		}
		return num;
		console.log("处理后数据："+num);
	}
	//获取基本显示信息
	$scope.getChargerDetail=function () {
		// 获取桩站详情
		$scope.chargerDetail=localStorage.getItem("chargerDetail"); //获取缓存的桩站信息
		//组装桩类型数据
		if($scope.chargerDetail.chargerType=="1"){
			$scope.chargerDetailType="直流 快充"
		}else if($scope.chargerDetail.chargerType=="2"){
			$scope.chargerDetailType="交流220 慢充"
		}
		//获取预约信息
		if($stateParams.appointingId){
			$scope.appointingId=$stateParams.appointingId;
		}
		var postData={userCard:userCard}
		scCodeService.getOngoingOperation(postData).then(function(data){
			console.log(data.data);
			if(data.code == "200"){
					if(data.data){
					$scope.appointDetail=data.data.reservationList;
					$scope.mainRate=JSON.parse(localStorage.getItem("mainRate")); //获取预约、充电、服务费率
					//组装预约剩余时间和费用
					var current=new Date(); //获取当前时间
					current=(current.getTime()-$scope.appointDetail.startTime)/1000; //计算当前时间与开始时间的时间差
					var total=2*60*60;
					var surplusTimeSet = setInterval(function() {
						current++;
						if(current<total){
							$scope.estimatesFee=$scope.intToFloat(current*$scope.mainRate);
							var leave1=parseInt(total-current)%(24*3600);
							var sh=Math.floor(leave1/3600)+"小时";
							var leave2=leave1%3600;
							var sm=Math.floor(leave2/60)+"分钟";
							$scope.surplusTime=sh+sm;
						}else{ //若预约超时，则隐藏开始充电按钮
							clearInterval(surplusTimeSet);
							$scope.loadingToastSet("订单生成中...");
							$scope.surplusTime="预约超时";
							$scope.estimatesFee=$scope.intToFloat(total*$scope.mainRate);
							$scope.isReservationNotOverTime="false";
							//订单推送超时处理
							$scope.orderPushTimeOut();

						}

	                }, 1000);
				}
			}else{
				Popup.notice('获取预约信息失败', 3000, function() {
                           console.log('ok')
                    });
			}
		})

	}
	$scope.getChargerDetail();
	//开始导航
	$scope.satNavigation=function (argument) {
		//起点
		$scope.startcoordinate=localStorage.getItem("startcoordinate");
		//终点
		$scope.endcoordinate=$scope.chargerDetail.coordinate;
		//跳转到高德地图api导航
		window.location.href="http://gaode.com/?r=39.904777,116.42526700000002,起点,39.99458,116.30444299999999,终点,0,0,,,,src=jsapi_r_0"
	}
	//取消预约
	$scope.cancelReservation=function () {
		$scope.loadingToastSet("取消预约中...");
		var postData = {
			reservationSn:$scope.appointDetail.reservationSn
		}
		scCodeService.cancelReservation(postData).then(function(data){
			console.log(data.data);
			if(data.code == "200"){
				//订单推送超时处理
				$scope.orderPushTimeOut();
			}else{
				$scope.loadingToastHide();
				Popup.notice('取消失败', 3000, function() {
                           console.log('ok')
                   	});
			}
		})
	}
	//订单推送超时处理
	$scope.orderPushTimeOut=function() {
		var num = 0;
        var pushTimeout = setInterval(function() {
            num++;
            if (num > 20) {
                clearInterval(pushTimeout);
                var postData = {
                    userId: userId,
                    status:"0"
                }
                scCodeService.getFundList(postData).then(function(data) {
                    if (data.code == "200") {
                        if (data.data.length !== 0) {
                            $scope.notPayCardNo = data.data[0].orderNo;
                             window.location.href = mainConfig.hostUrl+"index.html?#/orderPay/" + $scope.notPayCardNo;
                        } else {
                            $location.path("/myOrder/pending");
                        }
                    }
                })
            }
        }, 1000);
	}
	//点击开始充电
	$scope.startCharge=function(){
		var postData = {
            chargerId: $scope.chargerDetail.chargerId,
            userCard: userCard,
            chargerPlugNo: $scope.chargerDetail.plugNoList.portNo,
            token: token,
            source:mainConfig.source,
            merchantCode:mainConfig.merchantCode
        };
        $scope.loadingToastSet("开启充电中...");
		scCodeService.openCharge(postData).then(function(data){
			$scope.loadingToastHide();
			console.log(data.data);
			if(data.code == "200"){
				//获取开始时间
                var temp = new Date();
                var Y = temp.getFullYear() + '-';
                var M = (temp.getMonth()+1 < 10 ? '0'+(temp.getMonth()+1) : temp.getMonth()+1) + '-';
                var D = temp.getDate() + ' ';
                var h = temp.getHours();
                if(h<10){
                    h = "0" + h;
                }
                var m = temp.getMinutes();
                if(m<10){
                    m = "0" + m;
                }
                var s = temp.getSeconds();
                if(s<10){
                    s = "0" + s;
                } 
                var result = Y+M+D+h+":"+m+":"+s;
                var SMS = Date.parse(temp);
                // var regex = /\//g;
                // var result = (temp.toLocaleDateString("zh-cn") + ' ' + temp.toLocaleTimeString("en-GB",{hour12: false})).replace(regex, '-');
                localStorage.setItem("SMS", SMS);
                console.log(localStorage.getItem("SMS"));
                localStorage.setItem("startTime", result);
                //判断充电开启状态
               	$scope.openCharge = "true";
               	localStorage.setItem("openCharge", $scope.openCharge);
			    //chargerId and plugNo
			    localStorage.setItem("chargerId", $scope.chargerDetail.chargerId);
			    localStorage.setItem("plugNo", $scope.chargerDetail.plugNoList.portNo);
			    localStorage.setItem("rate", $scope.mainRate.chargerRate);
              	$location.path("/charging");
			}else{
				Popup.notice('取消失败', 3000, function() {
                           console.log('ok')
                    });
			}
		})
	}
});

// 站点详情
appointingApp.controller('stateDetailController',function($scope,$rootScope,scCodeService,$location,$state,$stateParams){
	$scope.stationDetail = {
		stationName:"环球中心充电站",
		parkingType:"1",
	};
	$scope.score=9;
	// tab 切换
	$scope.stateTab=0;
	$scope.pileD=false;
	$scope.pileC=true;
	$scope.stateFun = function(index){
		$scope.stateTab=index;
		$scope.pileC = $scope.stateTab == 0 ? true :false;
		$scope.pileD = $scope.stateTab == 0 ? false :true;
	};
	//获取站点详情
	$scope.getStationDetail = function(){
		var postData = {
			userId:"",
			stationId:""
		};
		scCodeService.getStationDetail(postData).then(function(data){
			if(data.code==200){
				$scope.stationDetail = data.data;
			}
		})
	};
});


